﻿using System;
using System.Collections.Generic;
using SqlParameter = System.Data.SqlClient.SqlParameter;
using SqlDbType = System.Data.SqlDbType;
using IDataReader = System.Data.IDataReader;

namespace GamePlusClassLibrary
{
    public class InformacaoSite
    {
        public int? Idf_Informacao_Site { get; set; }
        public int Idf_Usuario { get; set; }
        public int? Idf_Jogo { get; set; }
        public int Idf_Informacao_Tipo { get; set; }
        public DateTime Dta_Cadastro { get; set; }

        public void Save()
        {
            List<SqlParameter> param = new List<SqlParameter>();
            param.Add(new SqlParameter("@Idf_Usuario", SqlDbType.Int));
            param.Add(new SqlParameter("@Idf_Jogo", SqlDbType.Int));
            param.Add(new SqlParameter("@Idf_Informacao_Tipo", SqlDbType.Int));

            param[0].Value = DBNull.Value;
            param[1].Value = DBNull.Value;
            param[2].Value = DBNull.Value;

            if (this.Idf_Jogo.HasValue)
                param[1].Value = this.Idf_Jogo.Value;

            string sQuery = @"INSERT INTO InformacaoSite (Idf_Usuario, Idf_Jogo, Idf_Informacao_Tipo)
            VALUES (@Idf_Usuario, @Idf_Jogo, @Idf_Informacao_Tipo)";

            DataAccessLayer.ExecuteNonQuery(System.Data.CommandType.Text, sQuery, param);
        }

        public static List<InformacaoSite> List(int pTop, int pPage)
        {
            List<SqlParameter> param = new List<SqlParameter>();
            param.Add(new SqlParameter("@TOP", SqlDbType.Int));
            param.Add(new SqlParameter("@PAGE", SqlDbType.Int));
            param[0].Value = pTop;
            param[1].Value = pPage;
            
            string sQuery = @"
                SELECT  * FROM (
                SELECT	TOP 20 ROW_NUMBER() OVER(ORDER BY Dta_Cadastro DESC) AS Row,* 
                FROM	InformacaoSite ORDER BY Dta_Cadastro DESC
                ) as table_res
                WHERE Row BETWEEN ((@PAGE*@TOP)-(@TOP-1)) AND (@TOP * @PAGE)
            ";

            List<InformacaoSite> ls = new List<InformacaoSite>();

            using (IDataReader iDr = DataAccessLayer.ExecuteReader(System.Data.CommandType.Text, sQuery, param))
            {
                if (iDr.Read())
                {
                    InformacaoSite obj = new InformacaoSite();
                    obj.Idf_Informacao_Site = int.Parse(iDr["Idf_Informacao_Site"].ToString());
                    obj.Idf_Usuario = int.Parse(iDr["Idf_Usuario"].ToString());
                    obj.Idf_Jogo = iDr["Idf_Jogo"].Equals(DBNull.Value) ? (int?)null : int.Parse(iDr["Idf_Jogo"].ToString());
                    obj.Idf_Informacao_Tipo = int.Parse(iDr["Idf_Informacao_Site"].ToString());
                    obj.Dta_Cadastro = DateTime.Parse(iDr["Dta_Cadastro"].ToString());
                    ls.Add(obj);
                }
            }

            return ls;
        }
    }
}
